package com.qdaily.ui.ui.views.QDWebView.QDArticleWebViewFileCache;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * Created by song on 15/5/8.
 */
public class QDArticleWebViewFileDownloadSlave implements Runnable{

    private String url;
    private String targetDir;
    private String targetFileName;
    private DownloadInteface downloadInteface;

    public QDArticleWebViewFileDownloadSlave(String url, String targetDir, String targetFileName, DownloadInteface downloadInteface)
    {
        this.url = url;
        this.targetDir = targetDir;
        this.targetFileName = targetFileName;
        this.downloadInteface = downloadInteface;
    }

    @Override
    public void run() {
        String tmpPath = targetDir + "/" + targetFileName + ".tmp";
        try {
            InputStream source = requestInputStream(url); //請求源文件InputStream

            if (source == null)
            {
                downloadInteface.complete(url, targetFileName, targetDir, false);
                return;
            }
            fileWrite(source, tmpPath);

            File from = new File(targetDir, targetFileName + ".tmp");
            File to = new File(targetDir, targetFileName);
            if(from.exists())
                from.renameTo(to);
            downloadInteface.complete(url, targetFileName, targetDir, true);
        } catch (IOException e) {
            downloadInteface.complete(url, targetFileName, targetDir, false);
        }
    }

    /**
     * 根據資源URL地址取得資源輸入流
     * @param url URL地址
     * @return 資源輸入流
     * @throws IOException
     * */
    private InputStream requestInputStream(String url) throws IOException {
        InputStream result = null;
        HttpGet httpGet = new HttpGet(url);
        HttpClient httpClient = new DefaultHttpClient();
        HttpResponse httpResponse = httpClient.execute(httpGet);
        int httpStatusCode = httpResponse.getStatusLine().getStatusCode();
        if(httpStatusCode == HttpStatus.SC_OK) {
            HttpEntity httpEntity = httpResponse.getEntity();
            result = httpEntity.getContent();
        }
        return result;
    }

    /**
     * 文件寫入
     * @param in 數據源輸入流
     * @param path 文件路徑
     * */
    private void fileWrite(InputStream in, String path) throws IOException {
        File file = createFile(path);
        FileOutputStream fileOutputStream = new FileOutputStream(file);
        byte buffer[] = new byte[1024];
        int progress = 0;
        int readBytes = 0;
        while ((readBytes = in.read(buffer)) != -1) {
            progress += readBytes;
            fileOutputStream.write(buffer, 0, readBytes);
        }
        in.close();
        fileOutputStream.close();
    }

    /**
     * 根據文件路徑創建文件
     * @param path 文件路徑
     * @return 文件File實例
     * @return IOException
     * */
    private File createFile(String path) throws IOException {
        File file = new File(path);
        file.createNewFile();
        return file;
    }

    interface DownloadInteface{
        void complete(String url, String name, String filePath, boolean success);
    }
}

